package org.xxmi.cors.web;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.xxmi.cors.common.DownloadFile;
import org.xxmi.cors.common.FileUtils;
import org.xxmi.cors.model.UploadFile;
import org.xxmi.cors.model.Version;
import org.xxmi.cors.model.VersionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class Demo {

    private static final String SAVE_PATH = "E:/spring-boot-cors/upload/";

    @GetMapping("/hello")
    public Map hello(UploadFile file) {
        System.out.println(file);
        Map result = new HashMap();
        result.put("name", "不一样的感觉");
        return result;
    }

    @PostMapping("/upload")
    public Map upload(UploadFile uploadFile, HttpServletRequest request) {
        Map result = new HashMap();
        MultipartFile iconFile = uploadFile.getIcon();
        File saveFile = new File(SAVE_PATH);
        // 创建文件夹路径
        if (!saveFile.exists() && !saveFile.isDirectory()) {
            saveFile.mkdirs();
        }
        try {
            iconFile.transferTo(new File(SAVE_PATH + iconFile.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        result.put("msg", "上传成功");
        result.put("code", 200);
        return result;
    }

    /**
     * 下载文件
     *
     * @param fileName 文件名
     * @return
     */
    @RequestMapping(value = "/download/{fileName}", method = RequestMethod.GET)
    public void download(@PathVariable("fileName") String fileName, HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
        String downloadFileName = URLEncoder.encode("测试下载看好使不.gif", "UTF-8");
//        res.setContentType("application/x-jpg");
        res.setHeader("Content-Disposition", "attachment;filename=FileName.jpg");
//        res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
//        res.setHeader("Pragma", "no-cache");
//        res.setHeader("Expires", "0");
        // 如何想让前端取到这个自定义属性必须在 Cors.java 中配置 corsConfiguration.addExposedHeader("custom-aa");
        res.setHeader("custom-aa", URLEncoder.encode("我的自定义header属性", "UTF-8"));
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(SAVE_PATH
                    + fileName)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("success");
//        https://www.cnblogs.com/studyCenter/p/6665171.html
    }

    @DeleteMapping("/array/{ids}")
    public Map array(@PathVariable Long[] ids) {
        Map result = new HashMap();
        result.put("ids", ids);
        return result;
    }

    @DeleteMapping("/array")
    public Map array2(@RequestParam Long[] ids) {
        Map result = new HashMap();
        result.put("ids", ids);
        return result;
    }

    @DeleteMapping("/array2")
    public Map array2(@RequestParam String[] ids) {
        Map result = new HashMap();
        result.put("ids", ids);
        return result;
    }

    @GetMapping("/version")
    public Map versions(@RequestParam Version[] list) {
        Map result = new HashMap();
        result.put("key", list);
        return result;
    }


    @GetMapping("/version/form")
    public Map versionForm(VersionForm form) {
        Map result = new HashMap();
        result.put("key", form);
        return result;
    }

    @PostMapping("/version/form")
    public Map versionFormBody(@RequestBody VersionForm form) {
        Map result = new HashMap();
        result.put("key", form);
        return result;
    }


    @GetMapping("/download")
    public Map download(@RequestParam(value = "taskId", required = true) Integer taskId, HttpServletRequest request, HttpServletResponse response) {
        Map result = new HashMap();
        result.put("taskId", taskId);
        return result;
    }

}
